<template>
  <div>
    <base-modal :title="title" :show.sync="dialogVisible" width="600px" @closed="dialogVisible = false">
      <div class="modal-content">
        <!-- start 故障节点 -->
        <el-form :model="faultForm" ref="faultForm" label-position="top" :rules="rules" v-if="renderForm">
          <!-- 可选上级 -->
          <el-form-item :label="$t('faultLibrary.faultObject.label3')" prop="parentDesc" :rules="[{ required: true, message: t('common.base.pleaseSelect'), trigger: ['blur'] }]">
            <div @click="showFaultDoalog">
              <el-input v-model="faultForm.parentDesc" placeholder="" readonly></el-input>
            </div>
          </el-form-item>

          <el-form-item :label="$t('common.base.title')" prop="faultDesc">
            <el-input v-model="faultForm.faultDesc" :maxlength="100" :placeholder="$t('common.placeholder.input2')" @blur="faultForm.faultDesc = faultForm.faultDesc.trim()"> </el-input>
          </el-form-item>

          <el-form-item :label="$t('common.base.description1')" prop="faultContent">
            <el-input type="textarea" v-model="faultForm.faultContent" maxlength="5000" :placeholder="$t('common.base.tip.defaultPlaceholder')" :autosize="{ minRows: 2, maxRows: 6 }" @blur="faultForm.faultContent = faultForm.faultContent.trim()"> </el-input>
          </el-form-item>

          <!-- 自定义标签 -->
          <el-form-item :label="$t('common.base.classification')" prop="faultLabel">
            <el-input v-model="faultForm.faultLabel" :placeholder="$t('common.faultLibrary.classificationPlaceholder')" :rules="[{ required: false }]"> </el-input>
          </el-form-item>

          <el-form-item :label="$t('common.paas.formType.attachment')">
            <form-attachment :field="{isNull:1}" v-model="faultForm.attribute.attachment"></form-attachment>
          </el-form-item>
        </el-form>
        <!-- start 故障节点 -->

        <form-builder v-loading="loading" :style="formBuilderStyle" :fields="fields" ref="ruleForm" :value="ruleForm" @update="update"> </form-builder>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ $t('common.base.cancel') }}</el-button>
        <el-button type="primary" :loading="saveLoading" @click="submitForm">{{ isFromEnter ? $t('faultLibrary.startEnter') : $t('common.base.save') }}</el-button>
      </div>
    </base-modal>

    <!-- 选择故障清单弹窗 -->
    <choose-fault-dialog ref="chooseFaultDialog" form="register" :initData="initData" :task="task" @click="getParentData" />
  </div>
</template>

<script>
// api
import {
  solutionGetFields, // 获取解决方案表单字段
  solutionGetData, // 获取解决方案的详细数据
  solutionCreate, // 新建解决方案
  solutionEdit, // 编辑解决方案
  libraryCreate,
  libraryEdit,
} from '@src/api/Fault';
import * as FaultApi from '@src/api/Fault';
// components
import ChooseFaultDialog from '@src/modules/task/editAllot/components/PartSeviceList/components/ChooseFaultDialog.vue';

import { ceshi, solutionSearch1, material } from '@src/modules/faultLibrary/mode/solutionGetFields.js';
import * as FormUtil from '@src/component/form/util';
import MsgModel from '@model/MsgModel';
import { message } from '@src/util/message';
import { useFormTimezone } from 'pub-bbx-utils';
const { disposeFormSubmitTime } = useFormTimezone();
import { validateFaultDesc, formatFaultToLocale } from './common';
import { cloneDeep } from 'lodash'

const baseData = {
  // 上级故障描述
  parentDesc: '',
  // 级别
  faultLevel: 0,
  // 对象描述
  faultDesc: '',
  // 父级id
  parentId: '',
  // 自定义标签
  faultLabel: '',
  faultContent: '',
  attribute:{
    attachment:[]
  }
  
};

export default {
  // 解决方案
  name: 'FaultCompositeDialog',
  components: {
    [ChooseFaultDialog.name]: ChooseFaultDialog,
  },
  data() {
    return {
      loading: false,
      options: [],
      ruleForm: {
        // 父级id
        libraryId: '',
        // 描述
        solution_desc: '',
        // 除了描述外的其他表单数据
        attribute: {},
      },

      // 表单字段
      fields: [],
      // 用于存储选中知识库的对象数据
      knowledgeData: [],
      faultForm: cloneDeep(baseData),
      // 上级祖链描述
      parentDescAll: '',
      renderForm: true,
      saveLoading: false,
      rules: {
        faultDesc: [{ required: true, validator: validateFaultDesc, trigger: 'blur' }],
      },
    };
  },

  props: {
    value: {
      type: Boolean,
      default: false,
    },

    // 新建需要，记录父级id和当前级别
    createFaultData: {
      type: Object,
      default: () => ({}),
    },

    // 当前的id
    currentFaultSolutionId: {
      type: String,
      default: '',
    },

    // 来源：0:故障树创建（默认）   1:工单附加组件创建（工单附加组件）
    faultSource: {
      type: Number,
      default: 0,
    },
    // 工单信息
    task: {
      type: Object,
      default: () => ({}),
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
  },
  watch: {
    value(value) {
      if (!value) {
        this.initForm();
      }else {
        this.openDialog();
      }
    },
  },

  computed: {
    dialogVisible: {
      get() {
        return this.value;
      },

      set(val) {
        this.$emit('input', val);
      },
    },

    title: {
      get() {
        return this.createFaultData.id ? this.$t('common.base.edit') : this.$t('common.base.create');
      },
    },
    // 工单附加组件创建
    isFaultSource() {
      return this.faultSource === 1;
    },
    dialogBodyStyle() {
      return {
        height: this.isFaultSource ? 'calc(100vh - 260px);' : '400px',
        overflow: 'auto',
      };
    },
    formBuilderStyle() {
      return this.isFaultSource ? 'max-height:calc(100vh - 260px);' : 'max-height: 360px;';
    },
    isFromEnter() {
      return this.createFaultData.isStartEntry;
    },
  },

  methods: {
    initForm() {
      this.ruleForm = {
        // 父级id
        libraryId: '',
        // 描述
        solution_desc: '',
        // 除了描述外的其他表单数据
        attribute: {},
      };
      this.faultForm.parentDesc = '';
      this.knowledgeData = [];
    },
    /**
     * @description 获取Field
     */
    getField(type) {
      let field = this.fields.filter(item => item.formType == type)[0];
      return field;
    },

    openDialog() {
      this.saveLoading = false;
      this.faultForm = cloneDeep(baseData);
      this.$refs['faultForm']?.resetFields();

      this.loading = true;

      // 获取表单字段接口
      let port = [solutionGetFields];

      // 编辑类型获取详细数据
      if (this.createFaultData.solutionId) {
        // 获取详情数据
        port.push(() => {
          return solutionGetData({ solutionId: this.createFaultData.solutionId });
        });
      } else {
        // 新增解决方案时，父组件传递过来的数据
        port.push(this.getInitData);
      }
      if (this.createFaultData.parentId) {
        this.getFaultInfo();
      }

      Promise.all(
        port.map(item => {
          return item();
        })
      )
        .then(async (res) => {
          // 解决方法描述必填
          res[0].data.forEach(x => {
            if (x.fieldName === 'solution_desc'){
              x.isNull = 0;
            } 
          });
          this.fields = [...res[0].data];
          const descField = this.fields.find(v => v.fieldName === 'solution_desc') || {};
          descField.maxlength = 1000;
          // todo 本地数据模拟测试的
          // this.fields = [ ...material ]
          // const { solutionDesc, attribute, wikiDataValue, sparePartValue, serviceProjectsValue, materialValue } = solutionSearch1.data.data || res[1]?.data || {}
          let resultData = res[1]?.data || {};
          resultData = await FormUtil.initRichTextContent(this.fields, resultData);
          const { solutionDesc, attribute, wikiDataValue, sparePartValue, serviceProjectsValue, materialValue } = resultData;
          let source = this.createFaultData.solutionId ? { solution_desc: solutionDesc, ...attribute } : {};

          let formType = ['subSparePart', 'subServiceItem', 'subMaterials'];

          let obj = {
            subSparePart: sparePartValue,
            subServiceItem: serviceProjectsValue,
            subMaterials: materialValue,
          };

          this.ruleForm = FormUtil.initialize(this.fields, source);

          formType.forEach(item => {
            const fieldName = this.getField(item)?.fieldName || '';
            if (!fieldName) return;
            const list = (obj[item] || []).map(data => {
              const { id, detailId, attribute } = data;
              return { id: detailId, editId: id, ...attribute };
            });
            this.ruleForm[fieldName] = list;
          });
          const knowledgeField = this.getField('knowledge');
          if (knowledgeField) {
            const knowledgeFieldName = knowledgeField.fieldName || '';
            this.knowledgeData =
              wikiDataValue?.map(wikiData => {
                return { id: wikiData.detailId, title: wikiData.attribute?.title, editId: wikiData.id };
              }) || [];
            const formData = wikiDataValue?.map(wikiData => wikiData.detailId) || [];
            this.ruleForm[knowledgeFieldName] = knowledgeField.setting?.isMulti ? formData : formData[0];
          }

          // 设置表单公共字段
          const { libraryId, libraryDesc, id } = res[1]?.data || {};
          this.ruleForm.libraryId = libraryId;
          this.ruleForm.solutionId = id;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取故障详情
    async getFaultInfo() {
      try {
        // 参数传递
        const params = { faultId: this.createFaultData.parentId };
        if (this.taskId) params.taskId = this.taskId;
        const res = await FaultApi.faultDetail(params);

        // 编辑页面需要处理数据
        this.faultForm = formatFaultToLocale(res.data)
        
      } catch (e) {
        console.log(e);
      }
    },
    // 封装成异步(为了减少判断)，返回新建解决方案，父组件传递过来的数据
    getInitData() {
      const { parentId, parentDesc } = this.createFaultData || {};
      return new Promise(resolve => {
        resolve({
          status: 0,
          data: {
            libraryId: parentId,
            id: null,
            libraryDesc: parentDesc,
            attribute: {},
          },
        });
      });
    },

    update({ field, newValue, valueObj }) {
      let { fieldName, displayName } = field;
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }

      if (field.fieldName === 'knowledge') {
        this.knowledgeData = valueObj;
      }

      this.$set(this.ruleForm, fieldName, newValue);
    },

    // 将系统字段转为接口需要的格式
    switchSystemField(list, solutionDetailType) {
      return list.map(item => {
        // const { id } = item
        const noAttrKeys = ['id', 'detailId'];
        // const keys = Object.keys(item)

        // keys.map(key => {
        //   if(noAttrKeys.includes(key)) return;

        //   attribute.push({
        //     mapKey: key,
        //     mapValue: item[key]
        //   })
        // })
        const attribute = { ...item };
        noAttrKeys.forEach(key => {
          delete attribute[key];
        });
        // id：原数据列表返回的id，detailId是该表单记录的该类型控件数据id，attribute自定义字段储存 json
        return { id: item.editId, detailId: item.id, solutionDetailType, attribute };
      });
    },

    // 系统字段提交时的key
    systemSubmitKey(key) {
      const obj = {
        solution_desc: 'solutionDesc',
        subSparePart: 'sparePartValue',
        subServiceItem: 'serviceProjectsValue',
        subMaterials: 'materialValue',
        knowledge: 'wikiDataValue',
      };
      return obj[key];
    },

    // 系统字段转换为接口需要的格式
    systemFieldToParams(field) {
      const { fieldName } = field;

      let value = [];

      if (fieldName === 'knowledge') {
        value =
          this.knowledgeData?.map(v => {
            const { id, title, editId } = v;
            return {
              id: editId,
              detailId: id,
              solutionDetailType: 4,
              attribute: { title },
            };
          }) || [];
      } else if (['subSparePart', 'subServiceItem', 'subMaterials'].includes(fieldName)) {
        const solutionDetailType = { subSparePart: 1, subMaterials: 2, subServiceItem: 3 }[fieldName];
        value = this.switchSystemField(this.ruleForm[fieldName], solutionDetailType);
      } else {
        value = this.ruleForm[fieldName];
      }
      return {
        key: this.systemSubmitKey(fieldName),
        value,
      };
    },

    // 系统字段集合,因为有的系统字段的isSystem为0，因此这边直接枚举出来
    getSystemFieldsNameArr() {
      return ['knowledge', 'solution_desc', 'subSparePart', 'subServiceItem', 'subMaterials'];
    },

    getParams() {
      let attribute = {};
      let systemFieldsAttr = {};

      const systemFieldsNameArr = this.getSystemFieldsNameArr();
      // 将自定义字段放到attribute里
      this.fields.map(item => {
        const { fieldName } = item;

        if (!systemFieldsNameArr.includes(fieldName)) {
          attribute[fieldName] = this.ruleForm[fieldName];
        } else {
          const { key, value } = this.systemFieldToParams(item);
          systemFieldsAttr[key] = value;
        }
      });

      const { libraryId, solutionId } = this.ruleForm;
      return {
        libraryId,
        id: solutionId,
        attribute,
        ...systemFieldsAttr,
        enterState: this.faultSource === 1 ? 0 : 1,
        solutionSource: this.faultSource,
      };
    },

    async submitForm() {
      try {
        const validateRes1 = await this.$refs.faultForm.validate();
        if (!validateRes1) return;

        const validateRes = await this.$refs.ruleForm.validate();
        if (!validateRes) return;

        this.saveLoading = true;
        // 添加故障节点
        const res1 = await this.faultSubmit();
        if (!MsgModel.isSuccess(res1)) return message.error(res1.message);

        const port = this.createFaultData.solutionId ? solutionEdit : solutionCreate;
        const params = disposeFormSubmitTime(this.fields, this.getParams()); // 处理国际化日期时间数据转换
        params.libraryId = res1.data.id;
        if (this.task.id) {
          params.permissionsHide = true;
        }
        const res = await port(params);

        if (!MsgModel.isSuccess(res)) return message.error(res.message);

        if (this.task.id) {
          // 绑定工单
          const params1 = {
            taskId: this.task.id,
            taskNo: this.task.taskNo,
            faultId: res1.data.id,
            solutionId: res.data.id,
            faultDesc: res1.data.faultDesc,
            faultContent: res1.data.faultContent,
            attribute:res1.data.attribute
          };
          if (this.createFaultData.solutionId) {
            params1.id = this.createFaultData.id;
            params1.objDesc = this.createFaultData.objDesc;
          }
          await this.faultBindTask(params1, this.createFaultData.parentId);
        }

        this.dialogVisible = false
        
        if(this.task?.id) return;

        this.$emit('success', {
          ...res1.data,
          parentDesc: this.faultForm?.parentDesc,
          solutionDesc: res.data?.solutionDesc,
          isEdit: !!this.createFaultData.parentId,
          solutionId: res.data.id,
        });
      } catch (e) {
        this.saveLoading = false;
        console.log('submitForm: ', e);
      }

      // 关闭弹窗
      // this.dialogVisible = false
      // this.$emit('operateSuc', { ...res.data, parentDescAll: this.parentDescAll, isEdit: !!this.createFaultData.parentId})
    },
    // 新建故障请求
    async faultSubmit() {
      let params = {
        ...this.faultForm,
        faultSource: this.faultSource,
        enterState: this.faultSource === 1 ? 0 : 1,
      };
      if (this.task.id) {
        params.permissionsHide = true;
      }

      const port = this.createFaultData.parentId ? libraryEdit : libraryCreate;
      return await port(params);
    },
    // 绑定工单
    faultBindTask(params, isEdit = false) {
      let url = 'getTaskCardSave';
      if (isEdit) {
        url = 'getTaskCardEdit';
      }
      FaultApi[url](params).then(res => {
        if (!MsgModel.isSuccess(res)) return message.error(res.message);
        // 保存成功再掉用刷新列表的接口
        this.$emit('success')
      }).catch((error) => {
        console.log('faultBindTask: ', error);
      })
      
      this.$emit('operateSuc')

      if (this.isFromEnter) {
        this.$emit('startEnter');
      }
    },
    showFaultDoalog() {
      this.$refs.chooseFaultDialog.open({
        isSelectParent: true, // 是否在选上级
        defaultCheckedKeys: [this.ruleForm.parentId],
      });
    },
    // 选择上级
    getParentData(data) {
      this.faultForm.parentId = data.id;
      this.faultForm.faultLevel = data.faultLevel + 1;
      this.faultForm.parentDesc = data.faultDesc;
      this.parentDescAll = data.parentDescAll;
      this.renderForm = false;
      this.$nextTick(() => {
        this.renderForm = true;
      });
      this.$set(this.faultForm, 'parentDesc', data.faultDesc);
    },
  },
};
</script>

<style lang="scss">
.el-dialog__wrapper .prev-level-des {
  padding: 0 12px;
  .label {
    line-height: 1.4;
    padding: 0;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    color: #262626;
  }
}
</style>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  overflow: auto;
}
.el-dialog__wrapper .prev-level-des {
  padding: 0 12px;
  .label {
    line-height: 1.4;
    padding: 0;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    white-space: nowrap;
    color: #262626;
  }
}
.form-builder {
  padding: 0;
}

.modal-content{
  // max-height: 600px;
  // overflow-y: scroll;
}
::v-deep .base-modal-body {
  padding: 20px;
  .form-builder {
    width: 100%;
    padding: 0;
    .form-item {
      padding-left: 0;
    }

  }
}
</style>
